import axios from "axios";
import { UniAdapter } from "uniapp-axios-adapter";
import { useUserStrore } from "@/store";

// 每次请求都创建一个新的实例
const request = axios.create({
  baseURL: "https://example.com",
  timeout: 10000,
  adapter: UniAdapter, // 指定适配器
  headers: {}
});

request.interceptors.request.use((config) => {
  const userStore = useUserStrore();
  if (userStore.token && config.headers) {
    // 如果有token，则带上token
    config.headers["Authorization"] = `Bearer ${userStore.token}`;
  }
  return config;
});

request.interceptors.response.use((response) => {
  // 统一处理响应,返回Promise以便链式调用
  if (response.status === 200) {
    const { data } = response;
    if (data && data.code === 200) {
      return Promise.resolve(data);
    } else {
      return Promise.reject(data);
    }
  } else {
    return Promise.reject(response);
  }
});